import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
// 使用 createSlice 创建模块

// 定义模块初始数据
const initialState = {
  count: 0,
};
export const incrementAsync = createAsyncThunk("incrementAsync", (count) => {
  // 异步回调必须返回一个promise
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(count);
    }, 2000);
  });
});
const countSlice = createSlice({
  name: "c1",
  initialState,
  //   reducers 定义处理同步任务的actions
  reducers: {
    increment(state, action) {
      state.count += action.payload;
    },
    decrement(state, action) {
      state.count -= action.payload;
    },
  },
  //   extraReducers  用来处理异步actions
  extraReducers(build) {
    // build.addCase用来监测异步actions的状态
    build.addCase(incrementAsync.fulfilled, (state, action) => {
      state.count += action.payload;
    });
  },
});

// 暴露所定义的actions
export const { increment, decrement } = countSlice.actions;

export default countSlice.reducer;
